package com.tang.nacos.config;

/**
 * @Author tanglingyu
 * @Date: 2021/04/06/ 15:19
 * @Description
 */

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;


/**
 * mybatis 非分库分表配置
 */
@Configuration
@MapperScan(basePackages = "com.tang.nacos.dao", sqlSessionTemplateRef = "ds1SqlSessionTemplate")
public class MybatisConfig {

  // 主数据源 ds1数据源
  @Primary
  @Bean("ds1SqlSessionFactory")
  public SqlSessionFactory ds1SqlSessionFactory(@Qualifier("ds1DataSource") DataSource dataSource)
      throws Exception {
    SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
    sqlSessionFactory.setDataSource(dataSource);
    sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
        .getResources("classpath:mybatis/*.xml"));
    return sqlSessionFactory.getObject();
  }

  @Primary
  @Bean(name = "ds1TransactionManager")
  public DataSourceTransactionManager ds1TransactionManager(
      @Qualifier("ds1DataSource") DataSource dataSource) {
    return new DataSourceTransactionManager(dataSource);
  }

  @Primary
  @Bean(name = "ds1SqlSessionTemplate")
  public SqlSessionTemplate ds1SqlSessionTemplate(
      @Qualifier("ds1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
    return new SqlSessionTemplate(sqlSessionFactory);
  }
}
